<template>
  <div>
    <el-form label-width="80px" class="zero-form demo-ruleForm" :model="zeroForm" ref="zeroForm">
      <el-form-item label="课程标题"
                    prop="title" :rules="[
                      {required: true, message: '课程标题不能为空'}
                    ]">
        <el-input type="text" v-model="zeroForm.title" placeholder="请输入课程标题"></el-input>
      </el-form-item>

      <el-form-item label="总课时" required>
        <el-input-number v-model="zeroForm.nums" :min="0" :max="240"></el-input-number>
      </el-form-item>

      <el-form-item label="课程分类" required>
        <el-cascader
          :options="optionSubject"
          :show-all-levels="false"
          v-model="subjectList"
          :props="{label: 'title',value: 'id',children: 'children'}"
        >
        </el-cascader>
      </el-form-item>

      <el-form-item label="选择讲师" required>
        <el-select v-model="zeroForm.teacherId"
                   filterable
                   placeholder="点击搜索以选择讲师"
                   clearable
                   @focus="this.isFocus">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="课程价格" label-width="80px" required>
        <el-input placeholder="请输入价格" v-model="zeroForm.price">
          <template slot="append">元</template>
        </el-input>
      </el-form-item>

      <el-form-item label="课程封面">
        <el-upload
          action="http://localhost:9001/xiyun/service/subject/uploadIcon"
          list-type="picture-card"
          :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload"
          :limit="1">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>

      <el-form-item label="课程简介">
        <el-input
          type="textarea"
          placeholder="请输入内容"
          v-model="zeroForm.description"
          maxlength="240"
          show-word-limit
        >
        </el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  //TODO  在离开界面时,点击取消侧边栏的高亮显示会切换,需要将这效果清除
  import subject from "../../../../../api/subject";
  import teacher from "../../../../../api/teacher";
  export default {
    name: "Zero",
    // updated(){
    //   this.isUpdated = true
    //   console.log('updated')
    // },
    mounted() {
      // console.log('mounted')
      this.getTeachers()
      this.getSubjectSortList()
    },
    props:{
      page: 0
    },
    data(){
      return{
        isUpdated : true,  //页面是否更改,即用户是否输入表单内容
        options: [],  //讲师列表
        optionSubject: [],  //课程分类列表
        subjectList: [],  //得到的课程分类数组,待会需要经过转换
        zeroForm:{
          title: '',
          description: '',
          nums: 0,
          price: 0,
          icon: '',
          teacherId: '',
          parentId: ''
        }
      }
    },
    beforeRouteLeave(to,from,next) {
      // console.log(to.fullPath)
      if (!this.isUpdated){
        next()
      }else if (to.fullPath !== '/dashboard/subjectupload/1'){
        this.$confirm('该界面内容未保存, 是否离开?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() =>{
          next()
        }).catch(() =>{
          // console.log('取消')
        })
      }else {
        this.$refs['zeroForm'].validate(valid => {
          if (valid){
            // console.log('验证ok')
            let v = this
            this.$route.meta.success = true
            this.zeroForm.parentId = this.subjectList[this.subjectList.length - 1]

            subject.submit0(this.zeroForm)
              .then(resp => {
                // console.log(resp.data.subjectId)
                // 将课程id保存在路由中
                // this.$route.meta.subjectId = resp.data.subjectId


                //将获取到的课程id保存在Vuex中,此为异步操作,数据无法立刻保存至vuex中
                v.$store.commit('setSubjectId',resp.data.subjectId)

                //TODO  网络响应失败不应该进行路由跳转
                // if (resp.status !== 2000){
                //   this.$message.error('信息保存失败,请稍后重试')
                // }
                // this.$router.meta.success = false
                // console.log(resp)
                this.$message.success('基本信息已保存')
                next()
              }).catch(err => {
              console.log(err)
            })
          }else {
            // alert('error')
          }
        })
      }
    },
    methods:{
      //获取讲师列表
      getTeachers(){
        teacher.getTeacherList()
        .then(resp => {
          // console.log(resp.data.teachers)
          this.options = resp.data.teachers
        })
      },
      //获取课程分类列表
      getSubjectSortList(){
        subject.getSubjectSorted()
        .then(resp => {
          // console.log(resp.data.subjectSort)
          this.optionSubject = resp.data.subjectSort
        })
      },
      //TODO  为了解决验证页面是否进行过更改,如果页面已经发生了更改,那么当用户直接跳转到其他页面前,需要弹出提示框
      //判断教师选择框是否被选择
      isFocus(){
        // console.log('focus')
      },

      //课程封面上传
      handleCoverSuccess(res, file) {
        // console.log(res)// 上传响应
        console.log(URL.createObjectURL(file.raw))// base64编码
        this.zeroForm.icon = res.data.url
      },
      beforeCoverUpload(file) {
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      }
    }
  }
</script>

<style scoped>
  .zero-form{
    width: 66%;
    margin: 36px auto;
  }
</style>
